package com.aspect;

import com.bean.LoginInfo;
import com.bean.User;
import com.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Aspect
@Component
public class AspectLogin {
    @Autowired
    UserService userService;

    @Around(value = "execution(public String com.controller.UserController.login(..))")
    public Object logging(ProceedingJoinPoint point) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        String time = formatter.format(date);

        //访问目标方法的参数：
        Object[] args = point.getArgs();
        String name = ((User) args[0]).getName();
        userService.insertLoginInfo(new LoginInfo(name, time, ip));

        //执行原方法并获取返回结果
        Object ret = point.proceed(args);
        return ret;
    }
}
